//
//  ViewController.m
//  Item
//
//  Created by 刘炳举 on 12/14/15.
//  Copyright © 2015 Kelly. All rights reserved.
//

#import "ViewController.h"
#import "MainTabBarCon.h"
//#import "util/SoapWsUtil.h"
#import "tools.h"
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"

#define AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES
#define URL @"https://139.196.53.145:31102/WebServices4SLSM.asmx?op=DTSLogin4PHP"
NSInteger  sValue ;
@interface ViewController (){
}
@property (strong, nonatomic) IBOutlet UITextField *pName;
@property (strong, nonatomic) IBOutlet UITextField *pPwd;
@property (retain, nonatomic) IBOutlet UIButton *UnSave;
@property (retain, nonatomic) IBOutlet UIButton *Save;
@property (strong, nonatomic) IBOutlet UILabel *uNum;
@property (strong, nonatomic) IBOutlet UIButton *uLogin;

@end

@implementation ViewController
@synthesize webData, soapResults, xmlParser;


-(void) viewWillAppear:(BOOL)animated{

    [self.navigationItem setHidesBackButton:YES];
    
    
}
-(void) viewDidAppear:(BOOL)animated{

}
-(void) viewDidDisappear:(BOOL)animated{
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    // Do any additional setup after loading the view, typically from a nib.
    //self.uLogin.enabled = NO;
    
    //[self.navigationItem setTitle:@"欢迎登陆"];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getTxt) name:UITextFieldTextDidEndEditingNotification object:self.pName];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getTxt) name:UITextFieldTextDidChangeNotification object:self.pPwd];
    
    [self.navigationItem setTitle:@"欢迎登陆"];
    
    _pName.delegate = self;
    _pPwd.delegate = self;

}

-(void)initData{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"saveNum"] isEqualToString:@"YES"]) {
        _UnSave.hidden = YES;
        _pName.text = [user objectForKey:@"userName"];
    } else {
        _Save.hidden = YES;
        _pName.text = @"";
    }

}


-(void)getTxt{

}
- (IBAction)saveNum:(id)sender {
    _Save.hidden = YES;
    _UnSave.hidden = NO;
    
}
- (IBAction)unsaveNum {
    _Save.hidden = NO;
    _UnSave.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    [textField resignFirstResponder];
}

- (IBAction)Login {
    
    recordResults = NO;
    NSString *soapMsg = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                         "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                         "<soap:Body>\n"
                         "<DTSLogin4PHP xmlns=\"http://tempuri.org/\">\n"
                         "<userID>%@</userID>\n"
                         "<password>%@</password>\n"
                         "</DTSLogin4PHP>\n"
                         "</soap:Body>\n"
                         "</soap:Envelope>\n", _pName.text, _pPwd.text];
    NSLog(@"soap:%@",soapMsg);
    //请求发送到的路径
    NSURL *url = [NSURL URLWithString:URL];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%lu", (unsigned long)[soapMsg length]];
    
    //以下对请求信息添加属性前四句是必有的，第五句是soap信息。
    [theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [theRequest addValue: @"http://tempuri.org/DTSLogin4PHP" forHTTPHeaderField:@"SOAPAction"];
    
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
    
    //请求
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    
    //如果连接已经建好，则初始化data
    if( theConnection )
    {
        webData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"theConnection is NULL");
    }

    MainTabBarCon* toMain = [self.storyboard instantiateViewControllerWithIdentifier:@"MainTabBar"];
    [self.navigationController pushViewController:toMain animated:NO];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
   // if(self.pNum.text.length>0){
        //if([self.pNum.text isEqualToString:self.uNum.text]){
     
            
            //if ([_pPwd.text isEqualToString:[user objectForKey:@"password"]]) {
               // MainTabBarCon* toMain = [self.storyboard instantiateViewControllerWithIdentifier:@"MainTabBar"];
                //[self.navigationController pushViewController:toMain animated:NO];
                [user setObject:@"yes" forKey:@"login"];
                [user setObject:self.pName.text forKey:@"userName"];
                [user setObject:self.pPwd.text forKey:@"password"];
                if (_UnSave.hidden) {
                    [user setObject:@"YES" forKey:@"saveNum"];
                    [user setObject:_pName.text forKey:@"userName"];
                } else {
                    [user setObject:@"NO" forKey:@"saveNum"];
                }
          //  } else {
          //      NSString *message = @"密码错误";
          //      [self showAlart:message];
          //  }
      //  }else{
//            NSString *message = @"验证码错误";
//            [self showAlart:message];
//        }
//        
//    }else{
//        NSString *message = @"请输入验证码";
//        [self showAlart:message];
//    }
}
//网址为https开头时需要
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){
        
        [[challenge sender]  useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
        
        [[challenge sender]  continueWithoutCredentialForAuthenticationChallenge: challenge];
        
    }
    
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength: 0];
    NSLog(@"connection: didReceiveResponse:1");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
    NSLog(@"connection: didReceiveData:2");
    
}

//如果电脑没有连接网络，则出现此信息（不是网络服务器不通）
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"ERROR with theConenction");
    [connection release];
    [webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"3 DONE. Received Bytes: %lu", (unsigned long)[webData length]);
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@",theXML);
    [theXML release];
    
    //重新加載xmlParser
    if( xmlParser )
    {
        [xmlParser release];
    }
    
    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities: YES];
    [xmlParser parse];
    
    [connection release];
    //[webData release];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
   attributes: (NSDictionary *)attributeDict
{
    NSLog(@"4 parser didStarElemen: namespaceURI: attributes:");
    
    if( [elementName isEqualToString:@"ReturnMessage"])
    {
        if(!soapResults)
        {
            soapResults = [[NSMutableString alloc] init];
        }
        recordResults = YES;
    }
    
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"5 parser: foundCharacters:");
    
    if( recordResults )
    {
        [soapResults appendString: string];
    }
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"6 parser: didEndElement:");
    
    if( [elementName isEqualToString:@"ReturnMessage"])
    {
        recordResults = FALSE;
       // greeting.text = [[[NSString init]stringWithFormat:@"第%@时区的时间是: ",nameInput.text] stringByAppendingString:soapResults];
        [soapResults release];
        soapResults = nil;
        NSLog(@"hoursOffset result");
    }
    
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
    NSLog(@"-------------------start--------------");
}
- (void)parserDidEndDocument:(NSXMLParser *)parser{
    NSLog(@"-------------------end--------------");
}
-(void)showAlart:(NSString*)msg
{
    UIAlertController* alart = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alart animated:YES completion:nil];
    UIAlertAction* OKAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alart addAction:OKAction];

}

- (void)dealloc {
    [_UnSave release];
    [_Save release];
    [super dealloc];
}
- (IBAction)View_TouchDown:(id)sender {
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}
@end
